package com.dcits.servicemanagement.controller;

import com.dcits.servicemanagement.entity.SysUser;
import com.dcits.servicemanagement.exception.NotLoginException;
import com.dcits.servicemanagement.service.SysRoleService;
import com.dcits.servicemanagement.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname LoginController
 * @Description 登录控制层
 * @Version 1.0.0
 * @Date 2022/4/22 10:05
 * @Created by hejle
 */

@Slf4j
@Controller
public class LoginController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    UserDetailsService userDetailsService;



    @RequestMapping("/login")
    public String login(){
        return "loginPage";
    }

    @RequestMapping("/register")
    public String register(){
        return "registerPage";
    }

    @RequestMapping("/verify")
    public String verify(@Param("account") String account, @Param("password") String password, Model model) {
        HashMap<String, Object> map = new HashMap<>();
        try{
            User user = (User) userDetailsService.loadUserByUsername(account);
            log.info(String.valueOf(user));
            model.addAttribute("username",user.getUsername());
            return "index";
        }catch (NotLoginException e){
            model.addAttribute("msg",e.getMessage());
            return "loginError";
        }

    }

    @RequestMapping("/registerSubmit")
    public String registerSubmit(@Param("account") String account,@Param("username") String username,
                                 @Param("password") String password, @Param("department") String department){
        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        SysUser sysUser = new SysUser(account,username,encoder.encode(password));
        sysUserService.insert(sysUser);


        return "loginPage";


    }
}
